package com.alveole.events.handlers;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import javax.enterprise.context.ApplicationScoped;

import org.apache.commons.beanutils.BeanUtils;

import com.alveole.events.browser.BrowserEvent;
import com.alveole.events.browser.BrowserEventFactory;
import com.alveole.events.server.ServerEvent;
import com.alveole.events.server.ServerEvents;
import com.alveole.objects.BrowserSession;
import com.alveole.tools.Logger;

@ApplicationScoped
public class BrowserEventHandler {
	public String process(BrowserSession browserSession, Map<String,String[]> requestMap)
	{	
		Logger.log(Logger.USERRUN, "Browser Event - " + browserSession.getUser().getLogin() + " ");
		for (String key : requestMap.keySet())
		{
			Logger.log(Logger.USERRUN, key +": {"); 
			String [] values = requestMap.get(key);
			Logger.log(Logger.USERRUN, values);
			for (String value : values)
				Logger.log(Logger.USERRUN, value + " ");

			Logger.log(Logger.USERRUN, "} - ");
			
		}
		Logger.logln(Logger.USERRUN, "");
		
		String [] c = requestMap.get("command");
		String command;
		if (c.length>0) command = c[0];
		else command="";
		BrowserEvent browserEvent = BrowserEventFactory.createBrowserEvent(command);
		try {
			BeanUtils.populate(browserEvent, requestMap);
		} catch (IllegalAccessException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List <ServerEvent> serverEvents = browserEvent.getServerEvents(browserSession);
		
		return ServerEvents.toJSON(serverEvents);
		
	}
	
}
